<template>
  <div class="page">
    <div class="searchBox">
      <input type="search" v-model="name" placeholder="请输入关键字..." enterkeyhint="search" @keyup.enter="handleSearch"
        class="ipt" ref="searchInput" />
      <van-icon name="search" size="20" color="#40a9ff" class="searchIcon" @click="handleSearch" />
    </div>
    <div class="container mt15">
      <div class="menuBox">
        <div v-for="item in menuTypes" :key="item.id"
          :class="['menu-item', 'fs26', { active: activeIndex === item.id }]" @click="handleMenu(item.id)">
          {{ item.name }}
        </div>
      </div>

      <!-- 菜单列表 -->
      <div v-if="isShowSkeleton" class="contentBox pt20 bg-ff ml15">
        <van-skeleton title :row="5" />
      </div>
      <div v-else class="contentBox bg-ff ml15">
        <a href="javascript:;" v-for="item in list" :key="item.id" class="food-item flexBox aiCenter block"
          @click="goMenuDetail(item.id)">
          <div class="img-box">
            <img :src="handleImgSrc(item.photo_url)" alt="" class="food-img">
          </div>
          <div class="flexItem ml20">
            <div class="flexBox aiCenter flexBetween">
              <div class="fs28" v-html="highlightKeyword(item.name, name, 'highlight')"></div>
              <van-icon v-if="item.is_new" name="new-arrival-o" size="26" color="#64C303" />
            </div>
            <div class="fs26 f600 c-f00"><span class="fs22 mr2">¥</span>{{ item.fee }}</div>
          </div>
          <div class="add-icon flexBox aiCenter">
            <div v-if="selectedCounts[item.id] > 0" class="decrease textCenter"
              @click="handleFood(item, 'decrease', $event)">
              <van-icon name="minus" size="12" color="#40a9ff" />
            </div>
            <span v-if="selectedCounts[item.id]" class="checkNum fs24 c-333 textCenter ml15 mr15">
              {{ selectedCounts[item.id] }}
            </span>
            <div class="increase textCenter" @click="handleFood(item, 'increase', $event)">
              <van-icon name="plus" size="12" color="#ffffff" />
            </div>
          </div>
        </a>
      </div>
    </div>
    <div v-if="Object.keys(selectedCounts).length > 0" class="settlement bg-ff">
      <div class="flexBox flexBetween">
        <div class="fs28 ml30" @click="showPopup = true">共 <span class="c-f00">{{ totalCount }}</span> 件商品，合计：<span
            class="fs24 c-f00 mr5">¥</span><span class="f600 c-f00">
            {{ totalPrice }}</span>
        </div>
        <div class="goPay fs28 textCenter" @click="handlePay">去结算</div>
      </div>
    </div>

    <van-popup v-model:show="showPopup" position="bottom" round :style="{ height: 'auto', maxHeight: '70%' }" closeable
      :close-on-click-overlay="false" @click-close-icon="closePopup">
      <div class="mt100">
        <div class="flexBox aiCenter flexBetween pl20 pr20">
          <div class="fs26">已选购 <span class="c-f00">{{ totalCount }}</span> 件商品</div>
          <div class="flexBox aiCenter" @click="handleClearCart">
            <van-icon name="delete-o" size="18" />
            <span class="block ml10 fs24 c-999">清空购物车</span>
          </div>
        </div>
        <div class="contentBox bg-ff">
          <div v-for="item in allSelectedFoods" :key="item.id" class="food-item flexBox aiCenter">
            <div class="img-box">
              <img :src="handleImgSrc(item.photo_url)" alt="" class="food-img">
            </div>
            <div class="flexItem ml20">
              <div class="fs28">{{ item.name }}</div>
              <div class="fs26 f600 c-f00"><span class="fs22 mr2">¥</span>{{ item.fee }}</div>
            </div>
            <div class="add-icon flexBox aiCenter">
              <div v-if="selectedCounts[item.id] > 0" class="decrease textCenter"
                @click="handleFood(item, 'decrease', $event)">
                <van-icon name="minus" size="12" color="#40a9ff" />
              </div>
              <span v-if="selectedCounts[item.id]" class="checkNum fs24 c-333 textCenter ml15 mr15">
                {{ selectedCounts[item.id] }}
              </span>
              <div class="increase textCenter" @click="handleFood(item, 'increase', $event)">
                <van-icon name="plus" size="12" color="#ffffff" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { menuList } from '@/api/menu'
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { handleImgSrc } from '@/utils'
import { MenuList } from '@/types/menuTypes'
import { showConfirmDialog, showToast } from 'vant'
import orderStore from '@/store/modules/order'
import router from '@/router'
import menuStore from '@/store/modules/menu'
import { useRoute } from 'vue-router'
import { highlightKeyword } from '@/utils'

const order = orderStore()
const menu = menuStore()
const route = useRoute()
const activeIndex = ref(Number(sessionStorage.getItem('curMenuType')) || 1)
const name = ref('')
const searchInput = ref<HTMLInputElement>()
const showPopup = ref(false)
const isShowSkeleton = ref(true)

const menuTypes = ref([
  { id: 1, name: '热门美食' },
  { id: 2, name: '清淡小炒' },
  { id: 3, name: '时蔬类' },
  { id: 4, name: '凉拌类' },
  { id: 5, name: '红烧类' },
  { id: 6, name: '汤类' },
  { id: 7, name: '主食' }
])

const list = ref<MenuList[]>([])
// 选中的数量
const selectedCounts = ref<Record<number, number>>({})
// 选中的商品
const allSelectedFoods = ref<Record<number, MenuList>>({})

// 计算总价
const totalPrice = computed(() => {
  let price = 0
  Object.keys(selectedCounts.value).forEach(id => {
    const item = allSelectedFoods.value[Number(id)]
    if (item) {
      price += Number(item.fee) * selectedCounts.value[Number(id)]
    }
  })
  return price.toFixed(2)
})

// 计算总数量
const totalCount = computed(() => {
  return Object.values(selectedCounts.value).reduce((sum, count) => sum + count, 0)
})

const handleMenu = async (id: number) => {
  name.value = ''
  activeIndex.value = id
  await getList()
}

const handleSearch = async () => {
  // if (!name.value) {
  //   return showToast('请输入关键字')
  // }
  if (searchInput.value) {
    searchInput.value.blur()
  }
  await getList()
}

const handleFood = (item: MenuList, type: string, event: Event) => {
  event?.stopPropagation()
  event?.preventDefault()
  allSelectedFoods.value[item.id] = item

  if (type === 'increase') {
    selectedCounts.value[item.id] = (selectedCounts.value[item.id] || 0) + 1
  } else {
    // 确保数量不会小于0
    selectedCounts.value[item.id] = Math.max((selectedCounts.value[item.id] || 0) - 1, 0)

    // 如果数量为0，从选中列表中移除
    if (selectedCounts.value[item.id] === 0) {
      delete selectedCounts.value[item.id]
      delete allSelectedFoods.value[item.id]
    }
  }
  menu.setMenu(
    Object.values(allSelectedFoods.value)
      .map(food => ({
        id: food.id,
        name: food.name,
        fee: food.fee,
        photo_url: food.photo_url,
        quantity: selectedCounts.value[food.id] || 0
      })).filter(item => item.quantity > 0)
  )
}

const handlePay = () => {
  // const checkoutItems = Object.values(allSelectedFoods.value).map(food => ({
  //   ...food,
  //   quantity: selectedCounts.value[food.id] || 0
  // })).filter(item => item.quantity > 0)

  const checkoutItems = menu.menuItems
    .filter(item => item.quantity > 0)
    .map(item => ({ ...item }))

  order.setCart(checkoutItems)
  router.push('confirmOrder')
}

const goMenuDetail = (id: number) => {
  sessionStorage.setItem('curMenuType', activeIndex.value.toString())
  router.push(`/menu/detail/${id}`)
}

const closePopup = () => {
  showPopup.value = false
}

const handleClearCart = () => {
  showConfirmDialog({
    title: '清空购物车',
    message: '确定要清空购物车吗？',
    confirmButtonColor: '#40a9ff'
  }).then(async () => {
    menu.clearMenu()
    selectedCounts.value = {}
    allSelectedFoods.value = {}
    showToast('已清空')
    closePopup()
  }).catch(() => {
    return
  })
}

const getList = async () => {
  const params = {
    name: name.value,
    type: name.value ? undefined : activeIndex.value
  }
  const { data } = await menuList(params)
  if (data.code === 0) {
    isShowSkeleton.value = false
    list.value = data.data.entries
  }
}

onMounted(() => {
  getList()
  // 从menuStore恢复购物车数据
  const validMenuItems = menu.menuItems.filter(item => item.quantity > 0)

  if (validMenuItems.length > 0) {
    selectedCounts.value = validMenuItems.reduce((acc, cur) => {
      acc[cur.id] = cur.quantity
      return acc
    }, {} as Record<number, number>)

    // 恢复选中商品（取有效商品）
    allSelectedFoods.value = validMenuItems.reduce((acc, cur) => {
      // 优先从当前list取商品（避免 menuStore 中字段过时），如果没有再用menuStore的数据
      const matchedFood = list.value.find(item => item.id === cur.id) || cur
      acc[cur.id] = matchedFood
      return acc
    }, {} as Record<number, MenuList>)
  } else {
    // 没有有效商品时，清空选中状态（避免残留旧数据）
    selectedCounts.value = {}
    allSelectedFoods.value = {}
  }
})

onUnmounted(() => {
  const curRouteName = route.name as string
  if (!['menuDetail', 'confirmOrder'].includes(curRouteName)) {
    sessionStorage.removeItem('curMenuType')
  }
})
</script>

<style lang="scss" scoped>
.page {
  background: #F7F7F7;
  padding: 15px 15px 165px 15px;
  box-sizing: border-box;
  // height: calc(100vh - 20vh);
  overflow: hidden;
  position: relative;
}

.searchBox {
  height: 80px;
  background: #F2F2F2;
  border-radius: 120px;
  padding: 10px 20px;
  box-sizing: border-box;
  position: relative;

  .ipt {
    width: 90%;
    height: 100%;
    border: none;
    outline: none;
    font-size: 26px;
    color: #333;
    background: #F2F2F2;
    padding: 0 20px;
  }

  .searchIcon {
    position: absolute;
    right: 30px;
    top: 50%;
    transform: translateY(-50%);
  }
}

.container {
  display: flex;
  // gap: 20px;
  height: 100%;
}

.menuBox {
  width: 180px;
  overflow-y: auto;
  overscroll-behavior-y: contain;
  // scroll-chaining: none;
  overflow-x: hidden;

  .menu-item {
    padding: 15px 20px;
    border-radius: 10px;
    margin-bottom: 15px;
    text-align: center;
    transition: background 0.3s;

    &.active {
      background: #fff;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      font-weight: 700;
    }
  }

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: #ddd;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
  }
}

.contentBox {
  flex: 1;
  border-radius: 10px;
  padding: 10px 30px 20px 20px;
  overflow-y: auto;
  overscroll-behavior-y: contain;
  // scroll-chaining: none;
  overflow-x: hidden;

  .food-item {
    padding: 15px 0;
    border-bottom: 1px solid #f5f5f5;
    position: relative;

    &:last-child {
      border-bottom: none;
    }

    .img-box {
      width: 120px;
      height: 120px;
      border-radius: 50%;
      overflow: hidden;
      background: #f5f5f5;
    }

    .food-img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .add-icon {
      position: absolute;
      right: 0;
      bottom: 15px;

      .decrease {
        width: 33px;
        height: 33px;
        line-height: 40px;
        background: #FFFFFF;
        border: 1px solid #40a9ff;
        border-radius: 50%;
        font-weight: 600;
      }

      .increase {
        width: 33px;
        height: 33px;
        line-height: 40px;
        background: #40a9ff;
        border-radius: 50%;
        font-weight: 600;
      }

      .checkNum {
        // position: absolute;
        // top: -20px;
        // right: -20px;
        // width: 35px;
        // height: 35px;
        // border-radius: 50%;
        // background: #40a9ff;
      }
    }
  }

  // 适配 Chrome/Safari/Edge 等 Webkit 内核浏览器
  &::-webkit-scrollbar {
    width: 0; // 隐藏纵向滚动条（宽度设为0）
    height: 0; // 隐藏横向滚动条
  }

  // 适配 Firefox
  scrollbar-width: none; // 直接隐藏滚动条
  -ms-overflow-style: none; // 适配 IE
}

.settlement {
  border: 1px solid #EEEEEE;
  border-radius: 120px;
  height: 80px;
  line-height: 80px;
  box-sizing: border-box;
  position: absolute;
  bottom: 15px;
  left: 30px;
  right: 30px;
  // z-index: 2025;

  .goPay {
    background: #40a9ff;
    color: #fff;
    border-radius: 120px;
    width: 150px;
    height: 80px;
    line-height: 80px;
  }
}

:deep(.highlight) {
  color: #ff4d4f;
  font-weight: 600;
}
</style>